<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\admin\CateModel;
use app\model\admin\MiniUser;
use app\model\admin\Order;
use app\model\admin\OrderItem;
use app\model\admin\Pact;
use app\model\admin\Product;
use app\model\mini\OrderLog;
use app\service\OrderService;
use think\facade\Validate;
use think\Request;

class OrderController extends AdminBaseController
{
    public function getList(Request $request)
    {
        $params = $request->param();
        $user_ids = [];
        $goods_id = [];
        $order_ids1 = [];
        $order_ids2 = [];
        $order_ids = [];
        if (isset($params['nickname'])) {
            $user_ids = MiniUser::scope('where', ['nickname' => $params['nickname'] ?? ''])->column('id');
        }
        if (isset($params['goods_name'])) {
            $order_ids1 = Product::scope('where', ['name' => $params['goods_name'] ?? ''])->column('id');
        }
        if (isset($params['cate_id'])) {
            $order_ids2 =  OrderItem::where('cate_id', $params['cate_id'])->column('order_id');
            if (count($order_ids2)) {
                $order_ids = array_merge($order_ids1, $order_ids2);
            } else {
                $order_ids = $order_ids1;
            }
        }

        $list = Order::with(['orderItem' => function ($q) {
            $q->with(['refund' => function ($q) {
                $q->where('is_del', 0);
            }]);
        },  'user'])
            ->where(function ($q) use ($params, $user_ids) {
                if (isset($params['nickname'])) {
                    $q->whereIn('user_id', $user_ids);
                }
            })->where(function ($q) use ($params, $order_ids) {
                if (isset($params['cate_id']) || isset($params['goods_name'])) {
                    var_dump($order_ids);
                    $q->whereIn('id', $order_ids);
                }
            })->scope('where', $params)
            ->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($list);
    }
    // 发货
    public function sendGoods(Request $request)
    {
        $params = $request->param();
        $info = Order::with(['orderItem', 'refund' => function ($q) {
            $q->where('is_del', 0)->where('');
        }])->where('pay_status', 1)->find($params['id']);
        if (!isset($params['delivery_id']) || !isset($params['delivery_id'])) {
            return error('参数错误');
        }
        // if (count($info->refund)) {
        //     return error('当前订单还有退款未处理，请先处理退款');
        // }
        $is_send = true;
        foreach ($info->orderItem->toArray() as $key => $val) {
            if ($val['refund_status'] == 1) {
                // 有退款的订单
                $is_send = false; //不允许发货
                break;
            }
        }
        if (!$is_send) {
            return error('当前订单还有退款未处理，请先处理退款');
        }
        if ($info->order_status == 0) {
            $info->order_status = 1; //待收货
            $info->delivery_id = $params['delivery_id'];
            $info->send_time = time();
            $info->save();
            OrderLog::create([
                "order_id" => $params['id'],
                "message" => "商家填写物流单号进行发货"
            ]);
            // todo模版通知用户
            return success();
        } else {
            return error('当前订单不允许发货');
        }
    }
    public function changeExpressNo(Request $request)
    {
        $params = $request->param();
        $info = Order::with(['orderItem', 'refund' => function ($q) {
            $q->where('is_del', 0)->where('');
        }])->where('pay_status', 1)->find($params['id']);
        if (!isset($params['delivery_id']) || !isset($params['delivery_id'])) {
            return error('参数错误');
        }
        $is_send = true;
        foreach ($info->orderItem->toArray() as $key => $val) {
            if ($val['refund_status'] == 1) {
                // 有退款的订单
                $is_send = false; //不允许发货
                break;
            }
        }
        if (!$is_send) {
            return error('当前订单还有退款未处理，请先处理退款');
        }
        if ($info->order_status == 1) {
            // $info->order_status = 1; 
            $info->delivery_id = $params['delivery_id'];
            $info->send_time = time();
            $info->save();
            OrderLog::create([
                "order_id" => $params['id'],
                "message" => "商家修改物流单号进行发货"
            ]);
            // todo模版通知用户
            return success();
        } else {
            return error('当前订单不允许发货');
        }
        // return;
    }
    public function getOrderLog(Request $request)
    {
        $order_id = input('id');
        $list = OrderLog::where([
            "order_id" => $order_id
        ])->order('id', 'desc')->select();
        return success($list);
    }
    // 确认收货
    public function confirmReceive(Request $request)
    {
        $params = $request->param();
        $info = Order::with(['orderItem'])->where('pay_status', 1)->find($params['id']);
        if ($info->order_status == 1) {
            $info->order_status = 2; //已收货，交易完成
            // $info->delivery_id = $params['delivery_id'];
            $info->save();
            // todo模版通知用户
            OrderService::handleCommission($params['id']);
            // 结算收益
            return success();
        } else {
            return error('当前订单不允许确认收货');
        }
    }
    // 订单统计
    public function orderCensus(Request $request)
    {

        $params = $request->param();
        $params['pay_status'] = 1;

        $order_total_info = Order::scope('where', $params)->fieldRaw("SUM(total_price) as sum_total_price,SUM(total_num) as sum_total_num")->find();

        $order_ids = Order::scope('where', $params)->with(['orderItem'])->column('id');
        $order_cost_info = OrderItem::whereIn('order_id', $order_ids)->fieldRaw("SUM(cost) as sum_total_cost")->find();
        // var_dump($order_total_info);

        $total_price = $order_total_info->sum_total_price; //销售额
        $total_num = $order_total_info->sum_total_num; //销售数量



        $cost_price = $order_cost_info->sum_total_cost; //总成本

        $profit = number_format($total_price - $cost_price, 2); //利润


        // 待发货
        $wait_send_info = Order::scope('where', $params)->where('order_status', 0)->with(['orderItem'])->fieldRaw("SUM(total_num) as total_num")->find();

        $wait_send_num = $wait_send_info->total_num;   //待发货商品数量

        // 退款订单
        $refund_info = OrderItem::scope('where', $params)->where('refund_status', "<>", 0)->fieldRaw('SUM(refund_num) as refund_num')->find();
        $refund_num = $refund_info->refund_num;

        // $sale_price = Order::with(['orderItem'])->where("pid", 'null')->sum('total_price');
        return success([
            "refund_num" => $refund_num ?? 0, //退款商品数量
            "wait_send_num" => $wait_send_num ?? 0, //待发货商品数
            "total_price" => $total_price ?? 0,  // 销售额
            "total_num" => $total_num ?? 0,  // 销售总数
            "profit" => $profit ?? 0,   //利润
            "cost_price" => $cost_price ?? 0,  //成本
        ]);
    }
}
